package com.examplee.username.httpfrist_01;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.webkit.WebView;
import android.widget.ImageView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by usernamee on 2017/7/10.
 */

public class HttpThread extends Thread {
    String url;
    WebView webView;
    Handler handler;
    ImageView imageView;
//    public HttpThread(String url,WebView webView,Handler handler){
//        this.handler=handler;
//        this.url=url;
//        this.webView=webView;
//
//    }
    public HttpThread(String url,ImageView imageView,Handler handler){
        this.handler=handler;
        this.url=url;
        this.imageView=imageView;

    }
    @Override
    public void run() {
        try {
            URL httpUrl=new URL(url);
            HttpURLConnection connection= (HttpURLConnection) httpUrl.openConnection();
            connection.setReadTimeout(5000);
            connection.setRequestMethod("GET");
            connection.setDoInput(true);//得到一个输入流
            InputStream in=connection.getInputStream();
            FileOutputStream out=null;
            File downloadFile=null;
            String filename= String.valueOf(System.currentTimeMillis());//获取系统时间
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){

                File parent=Environment.getExternalStorageDirectory();//得到SD卡的根目录
               downloadFile=new File(parent,filename);
                //            存入到一个SD卡里
                out =new FileOutputStream(downloadFile);
            }
byte[] b=new byte[2*1024];
            int len;
            if (out!=null){
                while ((len=in.read(b))!=-1){
                    out.write(b,0,len);
                }
            }
            final Bitmap bitmap= BitmapFactory.decodeFile(downloadFile.getPath());

            handler.post(new Runnable() {
               @Override
               public void run() {
                   imageView.setImageBitmap(bitmap);
               }
           });
//
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.run();
    }
}
